package com.xy_pro.xymanager.controller;

import com.xy_pro.xymanager.dto.SearchScoreRequest;
import com.xy_pro.xymanager.entity.ScoreData;
import com.xy_pro.xymanager.entity.UserEntity;
import com.xy_pro.xymanager.payload.ErrorResponse;
import com.xy_pro.xymanager.payload.UploadResponse;
import com.xy_pro.xymanager.repository.ScoreDataRepository;
import com.xy_pro.xymanager.repository.UserRepository;
import com.xy_pro.xymanager.service.ScoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Optional;

@RestController
@RequestMapping("/api/score")
public class ScoreController {

    @Autowired
    private ScoreService scoreService;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private ScoreDataRepository scoreDataRepository;

    @PostMapping("/search")
    public ResponseEntity<?> searchScore(@RequestBody SearchScoreRequest searchRequest) {
        String title = searchRequest.title;
        String studentName = searchRequest.studentName;
        if (title.isEmpty()){
            ErrorResponse error = new ErrorResponse("标题不能为空");
            return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST);
        }
        if (studentName == null || studentName.isEmpty()){
            ErrorResponse error = new ErrorResponse("学生姓名不能为空");
            return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST);
        }
        Optional<UserEntity> studentOptional = userRepository.findByName(studentName);
        if (studentOptional.isPresent()) {/// /学生存在
            System.out.println("tile:" + title + ", studentName:" + studentName);
            Optional<ScoreData> data = scoreDataRepository.findScoreDataByNameAndTitle(studentName, title);
            if (data.isPresent()) {
                return new ResponseEntity<>(data.get().getData(), HttpStatus.OK);
            } else  {
                ErrorResponse error = new ErrorResponse("学生成绩不存在");
                return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST);
            }
        }

        ErrorResponse error = new ErrorResponse("学生成绩不存在");
        return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST);
    }


    @PostMapping("/upload")
    public ResponseEntity<?> uploadFile( @RequestParam("title") String title, @RequestParam("file") MultipartFile file) {
        // 检查文件是否为空
        System.out.println("title: " + title);
        if (file.isEmpty()) {
            ErrorResponse error = new ErrorResponse("请选择要上传的文件");
            return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST);
        }
        if(title.isEmpty()){
            ErrorResponse error = new ErrorResponse("标题不能为空！");
            return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST);
        }

        // 检查文件格式
        if (!file.getOriginalFilename().endsWith(".xlsx")) {
            ErrorResponse error = new ErrorResponse("请上传.xlsx格式的Excel文件");
            return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST);
        }

        try {
            // 处理Excel文件
            UploadResponse response = scoreService.processExcel(title, file);

            // 如果有错误，返回部分成功状态
            if (response.getFailedRows() > 0) {
                return new ResponseEntity<>(response, HttpStatus.PARTIAL_CONTENT);
            }

            // 全部成功
            return new ResponseEntity<>(response, HttpStatus.OK);

        } catch (Exception e) {
            ErrorResponse error = new ErrorResponse("上传文件失败: " + e.getMessage());
            return new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}
